import React, {useState} from "react";
import {Form, Input, Button, Divider, Space, Table, Modal, message} from "antd";
import {SyncOutlined} from "@ant-design/icons";
import FuncBtnGroup from "@/components/FuncBtnGroup";
import Moment from "moment";
import {FuncGroupsProps} from "@/components/FuncBtnGroup/constants";
import {IPageResponse, PageInfo} from "@/common/common";
import {ColumnsType} from "antd/lib/table";
import {axiosAddRole, axiosDeleteRole} from "@/common/apis/role";
import './index.scss'

interface IProps {
  pageResponse?: IPageResponse<any>
  onChangePage: (page: PageInfo) => any
  refreshCallBack: () => any
}

const RoleContent = (props: IProps) => {

  const [form] = Form.useForm();
  const [showModal, setShowModal] = useState(false);
  const {onChangePage, pageResponse, refreshCallBack} = props;

  const addRole = async (data: any) => {
    data.status = 1
    data.create_by = 1
    const res = await axiosAddRole(data);
    if (res.code == 0) {
      message.success("添加成功");
      refreshCallBack()
    }
  }

  const delRecord = async (ids: number[]) => {
    const res = await axiosDeleteRole(ids);
    if (res.code === 0) {
      message.success("删除成功");
      refreshCallBack()
    }
  }

  const doAddRoleAction = () => {
    form.validateFields().then((values) => {
      setShowModal(false)
      addRole(values)
    })
  }

  const renderTableOperation = (text: any, record: any) => {
    const funcBtnsProps: FuncGroupsProps = {
      btns: [
        {
          key: `del`,
          text: "删除",
          confirmMsg: "确认删除该警报吗？",
          para: [record.id],
          onClick: delRecord,
          dropdownVisible: false
        },
      ],
      placement: "bottomLeft",
      htmlType: "a",
    };
    const result: any[] = [];
    const funcs = FuncBtnGroup(funcBtnsProps);
    const len = funcs.length - 1;
    funcs.forEach((item, index) => {
      result.push(item);
      if (index < len) {
        result.push(<Divider type="vertical" key={"divd" + index}/>);
      }
    });
    return result;
  };

  const columns: ColumnsType<any> = [
    {
      title: "角色名称",
      dataIndex: "name",
      align: "center",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      },
    },
    {
      title: "角色Code",
      dataIndex: "code",
      align: "center",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      }
    },
    {
      title: "创建人",
      dataIndex: "operator",
      align: "center",
      render: (text: number) => {
        return <div>{text ? text : "-"}</div>;
      }
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      align: "center",
      render: (text: string) => {
        return <div>{text ? text : "-"}</div>;
      },
      sorter: (data1: any, data2: any) => {
        let diff = Moment(data1.created_at).valueOf() - Moment(data2.created_at).valueOf();
        if (diff === 0) {
          if ((data1.id || 0) > (data2.id || 0)) {
            diff = 1;
          } else {
            diff = -1;
          }
        }
        return diff;
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      align: "center",
      render: (text: any, record: any) => {
        return renderTableOperation(text, record);
      },
    },
  ];

  return (
    <div className="listContainer">
      <div className="bths">
        <Space size={10}>
          <Button onClick={() => setShowModal(true)}>
            {"新增"}
          </Button>
          <Button type="dashed" onClick={refreshCallBack}>
            <SyncOutlined/>
          </Button>
          {`-共${pageResponse?.pageInfo.total}条记录`}
        </Space>
      </div>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={pageResponse?.data}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageResponse?.pageInfo.page || 0,
          pageSize: pageResponse?.pageInfo.size || 5,
          total: pageResponse?.pageInfo.total || 0,
          pageSizeOptions: ["5", "10", "15", "20"],
          showTotal: (total) => `共 ${total} 条`,
          onChange: (pageNo, pageSize) => {
            onChangePage({page: pageNo, size: pageSize})
          },
        }}
      />

      <Modal
        title="添加一条记录"
        visible={showModal}
        cancelText="取消"
        okText="添加"
        onOk={() => doAddRoleAction()}
        onCancel={() => setShowModal(false)}
      >
        <Form form={form}>
          <Form.Item
            label="角色名称"
            name="name"
            rules={[{required: true, message: "Please input role name!"}]}
          >
            <Input/>
          </Form.Item>
          <Form.Item
            label="角色code"
            name="code"
            rules={[
              {required: true, message: "Please input role code!"},
              {max: 10, message: "The role code must be less than 10 words!"}
            ]}
          >
            <Input/>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleContent;
